package com.yafeng.utils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.Map;

public class CollectionUtils {

    /**
     * @param map 取值的集合
     * @param key 所想取值的集合的key
     * @return 返回key对应的value
     */
    public static String getMapValue(Map<String, Object> map, String key) {
        String result = null;
        if (map != null) {
            Iterator<String> iterable = map.keySet().iterator();
            while (iterable.hasNext()) {
                Object object = iterable.next();
                if (key.equals(object))
                    if (map.get(object) != null)
                        result = map.get(object).toString();
            }
        }

        return result;
    }

    public static  String getTokenByCookie(ServletRequest request, ServletResponse response) {
        System.out.println("进入getTokenByCookie");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        Cookie[] cookies = null;
        String token = null;
        try {

            cookies = httpServletRequest.getCookies();
            for (Cookie cookie : cookies) {
                if (cookie.getName().contains("token")) {
                    System.out.println("cookie.getValue()="+cookie.getValue());
                     token=cookie.getValue();

                }

            }
        } catch (Exception e) {
            return token;
        }

        return token;
    }
}
